package com.yq.tanhua.ui.chat.chatlist

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import com.blankj.utilcode.util.ToastUtils
import com.fmt.mvi.learn.gobal.log
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMTextMessageBody
import com.yq.tanhua.im.HxImFunction
import com.yq.tanhua.ui.detail.CommonRequestState
import kotlinx.coroutines.launch

/**
 * @author: user
 * @date: 2023/5/11
 */
class ChatListActivity : AppCompatActivity() {

    companion object {
        fun actionStart(context: Context, conversationId: String, chatType: Int) {
            val intent = Intent(context, ChatListActivity::class.java)
            intent.putExtra("conversationId", conversationId)
            intent.putExtra("conversationType", chatType)
            context.startActivity(intent);
        }
    }

    private val mViewModel: ChatListViewModel by viewModels()

    val imFunction = HxImFunction()

    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initData()
        setContent {
            Scaffold(
                topBar = {
                    ChatTitleBar()
                }
            ) { paddingValues ->
                Column(
                    modifier = Modifier
                        .padding(paddingValues)
                        .background(Color(0xFFEEEDED))
                        .fillMaxSize()
                ) {
                    ChatList(modifier = Modifier.weight(1f))
                    InputLayout()
                }
            }

        }
    }

    @Composable
    private fun InputLayout() {
        var textState by rememberSaveable(stateSaver = TextFieldValue.Saver) {
            mutableStateOf(TextFieldValue())
        }
        UserInputText(
            textFieldValue = textState,
            onTextChanged = { textState = it }
        )
    }


    @Composable
    private fun UserInputText(
        keyboardType: KeyboardType = KeyboardType.Text,
        onTextChanged: (TextFieldValue) -> Unit,
        textFieldValue: TextFieldValue
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(64.dp),
            horizontalArrangement = Arrangement.End
        ) {
            Surface {
                Box(
                    modifier = Modifier
                        .height(64.dp)
                        .weight(1f)
                        .align(Alignment.Bottom)
                ) {
                    BasicTextField(
                        value = textFieldValue,
                        onValueChange = { onTextChanged(it) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(start = 32.dp)
                            .align(Alignment.CenterStart),
                        keyboardOptions = KeyboardOptions(
                            keyboardType = keyboardType,
                            imeAction = ImeAction.Send//部分手机存在兼容问题，为解决，比如一加手机还是显示回车且键盘监听onSend无法触发 TODO
                        ),
                        keyboardActions = KeyboardActions(onSend = {

                            sendMsg(textFieldValue, onTextChanged)
                        }),
                        maxLines = 1,
                        cursorBrush = SolidColor(LocalContentColor.current),
                        textStyle = LocalTextStyle.current.copy(color = LocalContentColor.current)
                    )
                    val disableContentColor =
                        MaterialTheme.colorScheme.onSurfaceVariant
                    if (textFieldValue.text.isEmpty()) {
                        Text(
                            modifier = Modifier
                                .align(Alignment.CenterStart)
                                .padding(start = 32.dp),
                            text = "聊一聊~",
                            style = MaterialTheme.typography.bodyLarge.copy(color = disableContentColor)
                        )
                    }

                    if (textFieldValue.text.isNotEmpty()) {
                        Text(
                            text = "发送",
                            modifier = Modifier
                                .align(Alignment.CenterEnd)
                                .padding(4.dp)
                                .background(Color.Green)
                                .padding(6.dp)
                                .clip(RoundedCornerShape(4))
                                .clickable {
                                    sendMsg(textFieldValue, onTextChanged)
                                }
                        )
                    }
                }
            }
        }
    }


    fun sendMsg(textFieldValue: TextFieldValue, onTextChanged: (TextFieldValue) -> Unit) {
        textFieldValue.text.log()
        imFunction.sendTextMsg(
            textFieldValue.text,
            conversationId,
            object : EMCallBack {
                override fun onSuccess() {
                    //消息发送成功
                    ToastUtils.showShort("消息发送成功")
                    initData()
                    onTextChanged(TextFieldValue(""))

                }

                override fun onError(code: Int, error: String?) {
                    ToastUtils.showShort("消息发送失败")
                }

            })
    }

    lateinit var conversationId: String
    private fun initData() {
        conversationId = intent.getStringExtra("conversationId").toString()
        val conversationType = intent.getIntExtra("conversationType", 0)
        mViewModel.loadServerMessages(conversationId!!, conversationType)
    }


    @Composable
    private fun ChatTitleBar() {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(Color.White)
                .padding(10.dp)
        ) {
            Icon(
                Icons.Filled.ArrowBack,
                contentDescription = "",
                tint = Color.Black,
                modifier = Modifier
                    .align(Alignment.CenterStart)
                    .clickable {
                        finish()
                    },
            )
            Text(text = "标题", modifier = Modifier.align(Alignment.Center))
        }
    }

    @Composable
    private fun ChatList(modifier: Modifier = Modifier) {
        val listUiDataState = mViewModel.chatListUiState.collectAsState()
        when (listUiDataState.value.requestState) {
            is CommonRequestState.Loading -> {
                Box(modifier = Modifier.fillMaxSize()) {
                    Text(text = "加载重...", modifier = Modifier.align(Alignment.Center))
                }
            }

            is CommonRequestState.LoadFail -> {
                Box(modifier = Modifier.fillMaxSize()) {
                    Text(text = "加载失败", modifier = Modifier.align(Alignment.Center))
                }
            }

            is CommonRequestState.LoadSuccess -> {
                if (listUiDataState.value.chatList == null) {
                    Box(modifier = Modifier.fillMaxSize()) {
                        Text(text = "暂无数据", modifier = Modifier.align(Alignment.Center))
                    }
                } else {
                    Messages(listUiDataState.value.chatList!!, modifier,)
                }
            }
        }
    }

    @SuppressLint("CoroutineCreationDuringComposition")
    @Composable
    private fun Messages(messages: List<EMMessage>, modifier: Modifier = Modifier) {

        val state = rememberLazyListState()
        LazyColumn(modifier = modifier, state =state ) {
            for (index in messages.indices) {
                val content = messages[index]
                item {
                    Message(content)
                }
            }
        }
        //创建CoroutineScope
        val coroutineScope = rememberCoroutineScope()
        coroutineScope.launch {
            state.scrollToItem(messages.size-1,0)
        }
    }

    @Composable
    private fun Message(content: EMMessage) {
        when (content.type) {
            EMMessage.Type.TXT -> {
                val textBody = content.body as EMTextMessageBody
                if(textBody.message.contains("strangerQuestion")){//说明该条消息是打招呼的聊一聊信息

                    CustomMessage(message = content,agressCallback = {
                        //添加好友、
                        mViewModel.addContract(content.from)
                    })
                }else{
                    TextMessage(message = content)
                }
            }

            else -> {
                TextMessage(message = content)
            }
        }

    }
}